﻿using System;
using System.Text;
using System.IO;


namespace Utility
{
    namespace IO
    {
        public class Memory
        {
            public static string GetStringFromMemoryStream(ref MemoryStream strona)
            {
                byte[] serBuf = new byte[(int)strona.Length];

                strona.Position = 0;
                strona.Read(serBuf, 0, (int)strona.Length - 1);
                strona.Position = 0;
                //strona.Dispose(); //Close the stream to release the memory.
                return System.Text.Encoding.ASCII.GetString(serBuf);

                
            }
        }

        /// <summary>

        /// Filesystem

        /// </summary>

        public class FileSystem
        {
            /// <summary>
            /// tworzy sciezke (drzewo) katalogow bazujac na podanym stringu
            /// </summary>
            /// <example>na podstawie identity = abc, zwroci: a/b/c; dla identity = "", zwroci "";</example>
            /// <remarks>tworzy drzewo po kazdym znaku (max glebokosc: 9 znakow)</remarks>
            /// <param name="identity"></param>
            /// <returns></returns>
            public static string GeneratePathBaseOnString(string identity)
            {
                StringBuilder sb = new StringBuilder();
                int maxDeep = 9;
                if (identity.Length < maxDeep)
                {
                    maxDeep = identity.Length;
                }

                for (int i = 0; i < maxDeep; i++)
                {
                    sb.Append(identity[i]);
                    if (i != maxDeep - 1) sb.Append(Path.DirectorySeparatorChar); //w ostatniej iteracji nie dodawaj "/"
                }

                return sb.ToString();
            }

            /// <summary>
            /// zapisuje cala zawartosc stringu do pliku i zamyka uchwyt do pliku
            /// </summary>
            /// <param name="pathToFile"></param>
            /// <param name="content"></param>
            public static void FilePutContent(string pathToFile, string content, bool append = false)
            {
                FileMode openAs;
                if (append)
                {
                    openAs = FileMode.Append;
                }
                else
                {
                    openAs = FileMode.Create;
                }
                FileStream fs = new FileStream(pathToFile, openAs, FileAccess.Write);
                UTF8Encoding enc = new UTF8Encoding();
                byte[] bytes = enc.GetBytes(content);
                fs.Write(enc.GetBytes(content),0, bytes.Length);
                fs.Close();
            }

            public static string FileGetContent(string pathToFile)
            {
                string sContents = string.Empty;
                if (pathToFile.ToLower().IndexOf("http:") > -1)
                { // URL 
                    System.Net.WebClient wc = new System.Net.WebClient();
                    byte[] response = wc.DownloadData(pathToFile);
                    sContents = System.Text.Encoding.ASCII.GetString(response);
                }
                else
                {
                    // Regular Filename 
                    System.IO.StreamReader sr = new System.IO.StreamReader(pathToFile);
                    sContents = sr.ReadToEnd();
                    sr.Close();
                }

                return sContents;
            }

            // Copy directory structure recursively

            public static void copyDirectory(string Src, string Dst)
            {
                String[] Files;

                if (Dst[Dst.Length - 1] != Path.DirectorySeparatorChar)
                    Dst += Path.DirectorySeparatorChar;
                if (!Directory.Exists(Dst)) Directory.CreateDirectory(Dst);
                Files = Directory.GetFileSystemEntries(Src);
                foreach (string Element in Files)
                {
                    // Sub directories

                    if (Directory.Exists(Element))
                        copyDirectory(Element, Dst + Path.GetFileName(Element));
                    // Files in directory

                    else
                        File.Copy(Element, Dst + Path.GetFileName(Element), true);
                }
            }

            public static bool WriteBinarFile(byte[] fs, string filePath)
            {
                    MemoryStream memoryStream = new MemoryStream(fs);
                    FileStream fileStream = new FileStream(filePath, FileMode.Create);
                    memoryStream.WriteTo(fileStream);
                    memoryStream.Dispose();
                    fileStream.Dispose();
                    fileStream = null;
                    memoryStream = null;
                

                return File.Exists(filePath);
            }

            public static byte[] ReadBinaryFile(string filePath)
            {
                if (File.Exists(filePath))
                {
                    try
                    {
                        ///Open and read a file
                        FileStream fileStream = File.OpenRead(filePath);
                        byte[] res = ConvertStreamToByteBuffer(fileStream);
                        fileStream.Close();
                        return res;
                    }
                    catch
                    {
                        return new byte[0];
                    }
                }
                else
                {
                    return new byte[0];
                }
            }

            public static byte[] ConvertStreamToByteBuffer(System.IO.Stream theStream)
            {
                int b1;
                System.IO.MemoryStream tempStream = new System.IO.MemoryStream();
                while ((b1 = theStream.ReadByte()) != -1)
                {
                    tempStream.WriteByte(((byte)b1));
                }
                return tempStream.ToArray();
            }

            
        }

        
    }
}
